<template>
  <a-form :layout="formLayout" :form="form">
    <a-form-item
      label="Form Layout"
      :label-col="formItemLayout.labelCol"
      :wrapper-col="formItemLayout.wrapperCol"
    >
      <a-radio-group default-value="horizontal" @change="handleFormLayoutChange">
        <a-radio-button value="horizontal">
          Horizontal
        </a-radio-button>
        <a-radio-button value="vertical">
          Vertical
        </a-radio-button>
        <a-radio-button value="inline">
          Inline
        </a-radio-button>
      </a-radio-group>
    </a-form-item>
    <a-form-item
      label="Field A"
      :label-col="formItemLayout.labelCol"
      :wrapper-col="formItemLayout.wrapperCol"
    >
      <a-input
        placeholder="input placeholder"
        v-decorator="[
          'fieldA',
          { initialValue: fieldA, rules: [{ required: true, min: 6, message: '必须大于5个字符' }] },
        ]"
      />
    </a-form-item>
    <a-form-item
      label="Field B"
      :label-col="formItemLayout.labelCol"
      :wrapper-col="formItemLayout.wrapperCol"
    >
      <a-input
        placeholder="input placeholder"
        v-decorator="[
          'fieldB',
          { initialValue: fieldB, rules: [{ required: true, min: 6, message: '必须大于5个字符' }] },
        ]"
      />
    </a-form-item>
    <a-form-item :wrapper-col="buttonItemLayout.wrapperCol">
      <a-button type="primary" @click="handleSubmit">
        Submit
      </a-button>
    </a-form-item>
  </a-form>
</template>

<script>
export default {
  data() {
    this.form = this.$form.createForm(this);
    return {
      formLayout: "horizontal",
      fieldA: "Hello",
      fieldB: "",
    };
  },
  watch: {
    // fieldA(val) {
    //   if (val.length <= 5) {
    //     this.fieldAStatus = "error";
    //     this.fieldAHelp = "必须大于5个字符";
    //   } else {
    //     this.fieldAStatus = "";
    //     this.fieldAHelp = "";
    //   }
    // },
  },
  mounted() {
    setTimeout(() => {
      // this.form.setFieldsValue("fieldA", "Hello world");
      //动态对表单赋值
      this.form.setFieldsValue({ fieldA: "Welcome", fieldB: "Hello World" });
    }, 3000);
  },
  computed: {
    formItemLayout() {
      const { formLayout } = this;
      return formLayout === "horizontal"
        ? {
            labelCol: { span: 4 },
            wrapperCol: { span: 14 },
          }
        : {};
    },
    buttonItemLayout() {
      const { formLayout } = this;
      return formLayout === "horizontal"
        ? {
            wrapperCol: { span: 14, offset: 4 },
          }
        : {};
    },
  },
  methods: {
    handleFormLayoutChange(e) {
      this.formLayout = e.target.value;
    },
    handleSubmit() {
      this.form.validateFields((error, values) => {
        if (!error) {
          console.log(values);
          //校验通过后,同步给Data,根据字段映射
          Object.assign(this, values);
        }
      });
    },
  },
};
</script>
